package com.jz.control;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * @ClassName BaseServlet
 * @Description TODO
 * @Author MR_Liu
 * @Date 2021/7/6 0006 10:31
 * @Version 1.0
 */
@WebServlet("/base")
public class BaseServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        //反射-->发送什么请求，调用什么方法
        //1.获取请求路径
        String uri = req.getRequestURI();
        System.out.println(uri); //  User_Pro/demoTest.do
        //2.获取调用的方法名
        String methodName = uri.substring(uri.lastIndexOf("/")+1,uri.lastIndexOf("."));
        System.out.println(methodName);
        //3.获取类中Class类型
        Class<? extends BaseServlet> clazz = this.getClass();
        //4.获取方法对象 -->方法名   方法的参数类型
        try {
            Method m = clazz.getMethod(methodName,HttpServletRequest.class,HttpServletResponse.class);
            //5.调用
            m.invoke(this,req,resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
